package com.example.coolweather;

import static com.example.coolweather.constants.Constants.PROVINCE_URL;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.coolweather.databinding.ChooseAreaBinding;
import com.example.coolweather.db.City;
import com.example.coolweather.db.County;
import com.example.coolweather.db.Province;
import com.example.coolweather.util.HttpUtil;
import com.example.coolweather.util.Utility;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {
    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String COUNTY = "county";
    ChooseAreaBinding binding;

    public static final int LEVEL_PROVINCE = 0;//省级
    public static final int LEVEL_CITY = 1;//市级
    public static final int LEVEL_COUNTY = 2;//县级
    private int currentLevel = LEVEL_PROVINCE;//当前显示的省级列表 currentLevel=0;

    List<Province> provinceList;//省的集合数据
    List<City> cityList;//市的集合数据
    List<County> countyList;

    private Province selectedProvince;
    private City selectedCity;

    List<String> dataList = new ArrayList<>();//存放省份名称列表、市名称列表
    ArrayAdapter<String> adapter;

    ProgressDialog progressDialog;

//    private ProgressDialog progressDialog;
//
//    private ArrayAdapter<String> adapter;
//    private List<String> dataList = new ArrayList<>();
//
//    private List<Province> provinceList;
//    private List<City> cityList;
//    private List<County> countyList;
//    private Province selectedProvince;
//    private City selectedCity;
//    private int currentLevel;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = ChooseAreaBinding.inflate(inflater, container, false);

        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, dataList);
        binding.listView.setAdapter(adapter);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        binding.listView.setOnItemClickListener((adapterView, view, position, id) -> {
            if (currentLevel == LEVEL_PROVINCE) {
                selectedProvince = provinceList.get(position);
                queryCities();
            } else if (currentLevel == LEVEL_CITY) {
                selectedCity = cityList.get(position);
                queryCounties();
            }

        });

        binding.backButton.setOnClickListener(v -> {
            if (currentLevel == LEVEL_CITY) {
                queryProvinces();
            } else if (currentLevel == LEVEL_COUNTY) {
                queryCities();
            }
        });
        queryProvinces();
    }

    private void queryCounties() {
        binding.titleText.setText(selectedProvince.getProvinceName() + ":" + selectedCity.getCityName());
        binding.backButton.setVisibility(View.VISIBLE);

        countyList = LitePal.where("cityId=?",
                String.valueOf(selectedCity.getId())).find(County.class);
        if (countyList.size() > 0) {
            dataList.clear();
            countyList.forEach(item -> {
                dataList.add(item.getCountyName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel = LEVEL_COUNTY;
        } else {
            String url = PROVINCE_URL + "/" + selectedProvince.getProvinceCode() + "/" + selectedCity.getCityCode();
            queryFromServer(url, "county");
        }
    }

    private void queryCities() {
        binding.titleText.setText(selectedProvince.getProvinceName());
        binding.backButton.setVisibility(View.VISIBLE);

        cityList = LitePal.where("provinceId=?",
                String.valueOf(selectedProvince.getId())).find(City.class);
        if (cityList.size() > 0) {
            dataList.clear();
            cityList.forEach(item -> {
                dataList.add(item.getCityName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel = LEVEL_CITY;
        } else {
            String url = PROVINCE_URL + "/" + selectedProvince.getProvinceCode();
            queryFromServer(url, "city");
        }
    }

    private void queryProvinces() {
        binding.titleText.setText("中国(china)");
        binding.backButton.setVisibility(View.GONE);
        provinceList = LitePal.findAll(Province.class);
        if (provinceList.size() > 0) {
            dataList.clear();
            provinceList.forEach(item -> {
                dataList.add(item.getProvinceName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel = LEVEL_PROVINCE;
        } else {
            queryFromServer(PROVINCE_URL, "province");
        }
    }

    private void queryFromServer(String url, String type) {
        Log.d("test", url);
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "访问网络失败！", Toast.LENGTH_SHORT).show();
                    closeProgressDialog();
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //解析数据 放在子线程中
                String strJson = response.body().string();
                Log.d("test", "onResponse: " + strJson);
                boolean result = false;
                if ("province".equals(type)) {
                    result = Utility.handleProvinceResponse(strJson);//写入数据库表
                } else if ("city".equals(type)) {
                    result = Utility.handleCityResponse(strJson, selectedProvince.getId());
                } else if ("county".equals(type)) {
                    result = Utility.handleCountyResponse(strJson, selectedCity.getId());
                }
                if (result) {
                    if (PROVINCE.equals(type)) {
                        getActivity().runOnUiThread(() -> {
                            queryProvinces();
                        });
                    } else if (CITY.equals(type)) {
                        getActivity().runOnUiThread(() -> {
                            queryCities();
                        });
                    } else if (COUNTY.equals(type)) {
                        getActivity().runOnUiThread(() -> {
                            queryCounties();
                        });
                    }
                    closeProgressDialog();
                } else {
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(),
                                "数据解析失败", Toast.LENGTH_SHORT).show();
                        closeProgressDialog();
                    });
                }
                //显示数据 （再次调用queryProvinces() )

            }
        });
    }

    private void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getContext());
            progressDialog.setMessage("正在访问网络，请稍后！");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }
}